package com.zhangxujie.litewords.ui.cardview;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Outline;
import android.os.Bundle;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.zhangxujie.litewords.R;
import com.zhangxujie.litewords.api.AchievementUtil;
import com.zhangxujie.litewords.api.Const;
import com.zhangxujie.litewords.db.AppDatabase;
import com.zhangxujie.litewords.db.DBUtil;
import com.zhangxujie.litewords.entity.ReciteWords;
import com.zhangxujie.litewords.entity.Words;

import java.util.List;
import java.util.Locale;

public class PagerFragment extends Fragment implements TextView.OnEditorActionListener {
    private static final String ARG_DATA = "data";

    private PagerData mData;

    private ImageView mImageView;
    private TextView mContent;
    private TextView mWord;
    private EditText mWordEdit;
    private LinearLayout mSpellLayout;
    private Button mBtnCheckWord;
    private ImageView mWordSpeaker;
    private SharedPreferences mSpf;
    private TextView mWordId;

    private static boolean SWITCH_RECITE_1 = false;
    private static boolean SWITCH_RECITE_2 = false;
    private static boolean SWITCH_RECITE_3 = false;


    //读单词
    private TextToSpeech textToSpeech;


    /**
     * 通过静态方法获取Fragment实例，向Fragment传参数
     *
     * @param data 数据
     * @return Fragment
     */
    public static PagerFragment newInstance(PagerData data) {
        PagerFragment fragment = new PagerFragment();

        //使用FragmentArguments传递参数
        Bundle args = new Bundle();
        args.putSerializable(ARG_DATA, data);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mData = (PagerData) getArguments().getSerializable(ARG_DATA);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pager, container, false);

        //绑定控件
        initWidget(view);

        //ImageView设置圆角
        ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, mImageView.getWidth(), mImageView.getHeight(), 16);
            }
        };

        mImageView.setOutlineProvider(viewOutlineProvider);
        mImageView.setClipToOutline(true);

        SWITCH_RECITE_1 = mSpf.getInt(Const.RECITE_SETTING_REMEMBER, 0) == 1;
        SWITCH_RECITE_2 = mSpf.getInt(Const.RECITE_SETTING_2, 0) == 1;
        SWITCH_RECITE_3 = mSpf.getInt(Const.RECITE_SETTING_LOADIMG, 0) == 1;

        //加载网络图片
        if (SWITCH_RECITE_3 && mData.getmImageURL() != null && !mData.getmImageURL().equals("")) {
            Glide.with(this).load(mData.getmImageURL()).into(mImageView);
        } else {
            Glide.with(this).clear(mImageView);
        }

        //加载翻译到content
        if (mData.getmContent().indexOf("常用英语教材") != -1) {
            mContent.setText("为查询到该单词释义！");
        } else {
            mContent.setText(Html.fromHtml(mData.getmContent()));
        }

        //加载单词
        mWord.setText(mData.getmWord());

        //加载单词ID
        mWordId.setText(String.valueOf(mData.getmWordId()));

        if (SWITCH_RECITE_1) {
            if (SWITCH_RECITE_2) {
                mWord.setVisibility(View.INVISIBLE);
                mSpellLayout.setVisibility(View.VISIBLE);
                mContent.setVisibility(View.VISIBLE);
            } else {
                mWord.setVisibility(View.VISIBLE);
                mSpellLayout.setVisibility(View.INVISIBLE);
                mContent.setVisibility(View.INVISIBLE);
            }
        } else {
            mSpellLayout.setVisibility(View.INVISIBLE);
            mWord.setText(mData.getmWord());
            mContent.setText(Html.fromHtml(mData.getmContent()));
        }

        initListenr(view);

        return view;
    }

    private void initListenr(final View view) {
        final Context ctx = getContext();

        //检查单词拼写正确性
        mBtnCheckWord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWordEdit.getText().toString().toLowerCase().equals(mWord.getText().toString().toLowerCase())) {
//                    Toast.makeText(ctx, "拼写正确！", Toast.LENGTH_SHORT).show();

                    new Thread(){
                        @Override
                        public void run() {
                            Looper.prepare();
                            AppDatabase db = DBUtil.getDb(ctx);
                            ReciteWords info = new ReciteWords();
                            Words w = db.wordsDao().queryByWord(mWord.getText().toString());
                            info.word_id = w.id;
                            List<ReciteWords> reciteWordsList = db.reciteWordsDAO().findByWordId(w.id);
                            if (reciteWordsList == null || reciteWordsList.size() == 0){
                                db.reciteWordsDAO().insertAll(info);
                            }
                            int count = db.reciteWordsDAO().count();
                            Log.d("recite_num", "run: " + count);
                            Toast.makeText(ctx, "拼写正确！累计拼写正确单词数：" + db.reciteWordsDAO().count()+"", Toast.LENGTH_SHORT).show();
                            mWordEdit.setText("");//清空
                            //检查成就
                            AchievementUtil.checkReciteWordsNums(ctx, count);

                            Looper.loop();
                        }
                    }.start();

                } else {
                    Toast.makeText(getContext(), "错误！！！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //textToSpeech 初始化
        textToSpeech = new TextToSpeech(getContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
//                textToSpeech.setSpeechRate(Config.SPEAKER_SPEECH_RATE);
//                textToSpeech.setPitch(Config.SPEAKER_PITCH);

                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.US);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.e("error", "This Language is not supported");
                    } else {
                        //can be called
                    }
                } else {
                    Log.e("error", "Failed to Initialize");
                }
            }
        });

        //点击图片按钮 监听实践
        mWordSpeaker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                texttoSpeak(mWord.getText().toString());
            }
        });


        //软键盘添加回车查词功能
        mWordEdit.setOnEditorActionListener(this);
    }

    private void initWidget(View view) {
        mImageView = view.findViewById(R.id.image_view);
        mContent = view.findViewById(R.id.text_content);
        mWord = view.findViewById(R.id.text_word);
        mWordEdit = view.findViewById(R.id.text_word_edit);
        mSpellLayout = view.findViewById(R.id.spell_layout);
        mBtnCheckWord = view.findViewById(R.id.btn_word_check);
        mWordSpeaker = view.findViewById(R.id.btn_word_speak);
        mSpf = getActivity().getSharedPreferences("setting", Context.MODE_PRIVATE);
        mWordId = view.findViewById(R.id.word_id);





    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (actionId) {
            case EditorInfo.IME_ACTION_SEARCH:
                Log.e("BALLACK", "IME_ACTION_SEARCH");
                mBtnCheckWord.callOnClick();
                break;
            default:
                break;
        }
        return true;
    }


    private void texttoSpeak(String text) {

        if (!"".equals(text)) {
//            text = "Please enter some text to speak.";
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
        }

    }

    @Override
    public void onDestroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onDestroy();
    }
}
